package com.jsjosem.aftersales.utils;

import static com.zx.sdk.api.ZXManager.TAG;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.CityAdapter;
import com.jsjosem.aftersales.adapter.CountyAdapter;
import com.jsjosem.aftersales.adapter.DepartmentMenuAdapter;
import com.jsjosem.aftersales.adapter.DepartmentsCheckedAdapter;
import com.jsjosem.aftersales.adapter.MySimpleAdapter;
import com.jsjosem.aftersales.adapter.ProvinceAdapter;
import com.jsjosem.aftersales.api.CityApi;
import com.jsjosem.aftersales.api.DepartmentsApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.model.AppInfo;
import com.jsjosem.aftersales.data.response.CityResponse;
import com.jsjosem.aftersales.data.response.DepartmentsResponse;
import com.jsjosem.aftersales.data.response.DepartmentsUserResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.wang.avi.AVLoadingIndicatorView;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import retrofit2.Call;
import retrofit2.Retrofit;

public class CommonUtils {

    /**
     * 判断手机上是否安装了指定应用程序
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean appIsInstalled(Context context, String packageName) {
        List<ApplicationInfo> allApps = getAllInstalledAppList(context);
        if (CollUtil.isEmpty(allApps)) {
            return false;
        }
        for (ApplicationInfo app : allApps) {
            if (StrUtil.equals(app.packageName, packageName)) {
                return true;
            }
        }
        return false;
    }

    public static List<AppInfo> getInstalledAppList(Context context, List<String> packageNames) {
        List<ApplicationInfo> allInstalledAppList = getAllInstalledAppList(context);
        return allInstalledAppList.stream().filter(app -> packageNames.contains(app.packageName)).map(app -> {
            AppInfo appInfo = null;
            if (Objects.nonNull(app)) {
                appInfo = new AppInfo();
                appInfo.setAppName(getAppName(context, app.packageName));
                appInfo.setPkgName(app.packageName);
                appInfo.setIcon(getAppIcon(context, app.packageName));
            }
            return appInfo;
        }).collect(Collectors.toList());
    }

    public static List<ApplicationInfo> getAllInstalledAppList(Context context) {
        PackageManager packageManager = context.getPackageManager();
        return packageManager.getInstalledApplications(0);
    }

    /**
     * 打开高德地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     *
     * @param mode  出行方式
     * @param sname 当前位置
     * @param dname 终点名称
     */
    public static void openGaoDeMap(Context context, String sname, String mode, String dname) {
        if (mode == null) {
            mode = "0";
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setPackage("com.autonavi.minimap");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.parse("androidamap://route?sourceApplication=" + R.string.app_name + "&sname=" + sname + "&dname=" + dname + "&dev=0&m=0&t=" + mode));
        context.startActivity(intent);
    }

    /**
     * 打开百度地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * mode = transit（公交）、driving（驾车）、walking（步行）和riding（骑行）. 默认:driving
     * 当 mode=transit 时 ： sy = 0：推荐路线 、 2：少换乘 、 3：少步行 、 4：不坐地铁 、 5：时间短 、 6：地铁优先
     *
     * @param mode  出行方式
     * @param sname 当前位置
     * @param dname 终点名称
     */
    public static void openBaiduMap(Context context, String sname, String mode, String dname) {
        if (mode == null) {
            // 默认驾车路线
            mode = "driving";
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("baidumap://map/direction?origin=" + sname + "&destination=" + dname + "&mode=" + mode + "&sy=3&index=0&target=1?src=andr.jsjosem." + R.string.app_name));
        context.startActivity(intent);
    }

    /**
     * 打开腾讯地图（公交出行，起点位置使用地图当前位置）
     * <p>
     * 公交：type=bus，policy有以下取值
     * 0：较快捷 、 1：少换乘 、 2：少步行 、 3：不坐地铁
     * 驾车：type=drive，policy有以下取值
     * 0：较快捷 、 1：无高速 、 2：距离短
     * policy的取值缺省为0
     *
     * @param mode  出行方式
     * @param dname 终点名称
     */
    public static void openTencentMap(Context context, String sname, String mode, String dname) {
        if (mode == null) {
            mode = "drive";
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("qqmap://map/routeplan?type=" + mode + "&routeplan=" + sname + "&to=" + dname + "&policy=0&referer=" + R.string.app_name));
        context.startActivity(intent);
    }

    /**
     * 根据包名获取App的Icon
     *
     * @param pkgName 包名
     */
    public static Drawable getAppIcon(Context context, String pkgName) {
        try {
            if (null != pkgName) {
                PackageManager pm = context.getPackageManager();
                ApplicationInfo info = pm.getApplicationInfo(pkgName, 0);
                return info.loadIcon(pm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据包名获取App的名字
     *
     * @param pkgName 包名
     */
    public static String getAppName(Context context, String pkgName) {
        PackageManager pm = context.getPackageManager();
        try {
            ApplicationInfo info = pm.getApplicationInfo(pkgName, 0);
            return info.loadLabel(pm).toString();

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 展示大图
     *
     * @param context
     * @param imgUrls
     * @param position
     */
    public static void showBigImg(Context context, List<String> imgUrls, int position) {
        String url = imgUrls.get(position);
        Dialog dialog = new Dialog(context, R.style.normal_dialog_style);
        View dialogView = View.inflate(context, R.layout.dialog_enlarge_image, null);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        ImageView enlargeImage = dialogView.findViewById(R.id.enlarge_image);
        Glide.with(context)
                .load(url)
                .placeholder(R.drawable.rotate_pro)
                .error(R.drawable.load_failed_24dp)
                .override(600, 400)
                .into(enlargeImage);
        dialog.show();
    }

    /**
     * @param context
     * @param appInfoList
     * @param targetAddress
     */
    @SuppressLint("MissingPermission")
    public static void startNavi(Context context, List<AppInfo> appInfoList, String targetAddress) {
        if (StrUtil.isBlank(targetAddress)) {
            Toast.makeText(context, "没有地址，无法导航", Toast.LENGTH_SHORT).show();
            return;
        }
        for (AppInfo appInfo : appInfoList) {
            //获取设备所有的定位器
            switch (appInfo.getPkgName()) {
                case "com.autonavi.minimap":
                    CommonUtils.openGaoDeMap(context, "我的位置", null, targetAddress);
                    break;
                case "com.baidu.BaiduMap":
                    CommonUtils.openBaiduMap(context, "我的位置", null, targetAddress);
                    break;
                case "com.tencent.map":
                    CommonUtils.openTencentMap(context, "我的位置", null, targetAddress);
                    break;
            }
            return;
        }
    }

    /**
     * 选择图片
     *
     * @param activity
     */
    public static void selectPhoto(Activity activity) {
        Dialog dialog = new Dialog(activity, R.style.normal_dialog_style);
        View view = View.inflate(activity, R.layout.dialog_bottom, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        view.setMinimumHeight((int) (ScreenSizeUtils.getInstance(activity).getScreenHeight() * 0.23f));
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(activity).getScreenWidth() * 0.9f);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialog.show();

        Button takePhoto = view.findViewById(R.id.photograph);
        Button selectPhoto = view.findViewById(R.id.album);
        Button cancel = view.findViewById(R.id.cancel);

        takePhoto.setOnClickListener(v -> {
            //拍照
            PictureSelector.create(activity).openCamera(PictureMimeType.ofImage()).forResult(PictureConfig.REQUEST_CAMERA);
        });

        selectPhoto.setOnClickListener(v -> {
            //相册
            PictureSelector.create(activity).openGallery(PictureMimeType.ofImage()).maxSelectNum(9).minSelectNum(1).imageSpanCount(4).selectionMode(PictureConfig.MULTIPLE).enableCrop(true).freeStyleCropEnabled(true).compress(true).forResult(PictureConfig.CHOOSE_REQUEST);
        });

        cancel.setOnClickListener(v -> dialog.dismiss());
    }

    /**
     * 选择省市区
     *
     * @param activity
     * @param customerAddress
     * @param resProvince
     * @param resCity
     * @param resCounty
     */
    public static void getProvincesCity(Activity activity, TextView customerAddress, CityResponse resProvince, CityResponse resCity, CityResponse resCounty) {
        Dialog dialog = new Dialog(activity, R.style.background_darkens_dialog_style);
        View dialogView = View.inflate(activity, R.layout.dialog_customer_address, null);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(activity).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);

        TextView province = dialogView.findViewById(R.id.province);
        TextView city = dialogView.findViewById(R.id.city);
        TextView county = dialogView.findViewById(R.id.county);
        ListView areaList = dialogView.findViewById(R.id.area_list);
        AVLoadingIndicatorView avi= dialogView.findViewById(R.id.avi);

        List<CityResponse> provinceList = new ArrayList<>();
        List<CityResponse> cityList = new ArrayList<>();
        List<CityResponse> countyList = new ArrayList<>();

        ProvinceAdapter provinceAdapter = new ProvinceAdapter(activity, R.layout.customer_address_item_list, provinceList);
        CityAdapter cityAdapter = new CityAdapter(activity, R.layout.customer_address_item_list, cityList);
        CountyAdapter countyAdapter = new CountyAdapter(activity, R.layout.customer_address_item_list, countyList);

        AtomicInteger selectIndex = new AtomicInteger();
        Retrofit mRetrofit = RetrofitClient.getInstance();
        CityApi cityApi = mRetrofit.create(CityApi.class);
        Call<PageResponse<CityResponse>> getProvinces = cityApi.getByPid(0L);
        AsyncRequest<PageResponse<CityResponse>> requestProvinces = new AsyncRequest<>();
        avi.show();
        requestProvinces.sendRequest(getProvinces, res -> {
            avi.hide();
            if (res.getData() != null) {
                provinceList.clear();
                provinceList.addAll(res.getData());
                provinceAdapter.notifyDataSetChanged();
                areaList.setAdapter(provinceAdapter);
            }

        }, error -> {

        });

        areaList.setOnItemClickListener((parent, view, position, id) -> {
            if (selectIndex.get() == 0) {
                province.setText(provinceList.get(position).getName());
                city.setText("请选择");
                Call<PageResponse<CityResponse>> getCities = cityApi.getByPid(provinceList.get(position).getId());
                AsyncRequest<PageResponse<CityResponse>> requestCities = new AsyncRequest<>();
                avi.setVisibility(View.VISIBLE);
                areaList.setVisibility(View.GONE);
                requestCities.sendRequest(getCities, res -> {
                    avi.hide();
                    areaList.setVisibility(View.VISIBLE);
                    if (res.getData() != null) {
                        cityList.clear();
                        cityList.addAll(res.getData());
                        cityAdapter.notifyDataSetChanged();
                        areaList.setAdapter(cityAdapter);
                        selectIndex.set(1);
                        resProvince.setId(provinceList.get(position).getId());
                        resProvince.setName(provinceList.get(position).getName());
                        resProvince.setCitycode(provinceList.get(position).getCitycode());
                    } else {
                        customerAddress.setText(provinceList.get(position).getName());
                        dialog.dismiss();
                    }

                }, error -> {

                });

            } else if (selectIndex.get() == 1) {
                city.setText(cityList.get(position).getName());
                county.setText("请选择");
                Call<PageResponse<CityResponse>> getCounties = cityApi.getByPid(cityList.get(position).getId());
                AsyncRequest<PageResponse<CityResponse>> requestCounties = new AsyncRequest<>();
                avi.setVisibility(View.VISIBLE);
                areaList.setVisibility(View.GONE);
                requestCounties.sendRequest(getCounties, res -> {
                    avi.hide();
                    areaList.setVisibility(View.VISIBLE);
                    if (res.getData() != null) {
                        countyList.clear();
                        countyList.addAll(res.getData());
                        countyAdapter.notifyDataSetChanged();
                        areaList.setAdapter(countyAdapter);
                        selectIndex.set(2);
                        resCity.setId(cityList.get(position).getId());
                        resCity.setName(cityList.get(position).getName());
                        resCity.setCitycode(cityList.get(position).getCitycode());
                    } else {
                        String address = province.getText().toString() + "-" + city.getText().toString();
                        customerAddress.setText(address);
                        dialog.dismiss();
                    }

                }, error -> {

                });
            } else if (selectIndex.get() == 2) {
                resCounty.setId(countyList.get(position).getId());
                resCounty.setName(countyList.get(position).getName());
                resCounty.setCitycode(countyList.get(position).getCitycode());
                county.setText(countyList.get(position).getName());
                String address = province.getText().toString() + "-" + city.getText().toString() + "-" + county.getText().toString();
                customerAddress.setText(address);
                dialog.dismiss();
            }
        });

        province.setOnClickListener(v1 -> {
            areaList.setAdapter(provinceAdapter);
            province.setText("请选择");
            city.setText("");
            county.setText("");
            selectIndex.set(0);
        });

        city.setOnClickListener(v1 -> {
            areaList.setAdapter(cityAdapter);
            city.setText("请选择");
            county.setText("");
            selectIndex.set(1);
        });

        dialog.show();
    }

    /**
     * 部门菜单
     *
     * @param activity
     * @param imageView
     * @param textView
     * @param resDepartmentsUserResponse
     */
    public static void getDepartmentsMenu(Activity activity, ImageView imageView, TextView textView, DepartmentsUserResponse resDepartmentsUserResponse) {
        int currentPage = 1;
        View dialogView = View.inflate(activity, R.layout.dialog_department_menu, null);
        Dialog dialog = new Dialog(activity, R.style.background_darkens_dialog_style);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(activity).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);

        ListView deptLv = dialogView.findViewById(R.id.area_list);
        ListView deptUserLv = dialogView.findViewById(R.id.staff_list);
        AVLoadingIndicatorView avi = dialogView.findViewById(R.id.avi);

        AtomicInteger selectIndex = new AtomicInteger();
        List<DepartmentsResponse> departmentsResponses = new ArrayList<>();
        Map<String, List<DepartmentsUserResponse>> usersMap = new HashMap<>();
        DepartmentMenuAdapter adapter = new DepartmentMenuAdapter(activity, R.layout.area_item_list, departmentsResponses);

        Retrofit mRetrofit = RetrofitClient.getInstance();
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> request = new AsyncRequest<>();
        AsyncRequest<PageResponse<DepartmentsUserResponse>> requestDeptUser = new AsyncRequest<>();

        avi.setVisibility(View.VISIBLE);
        avi.show();
        request.sendRequest(getDepartments, res -> {
            departmentsResponses.addAll(res.getData());
            departmentsResponses.get(0).setSelected(true);
            for (int i = 0; i < res.getData().size(); i++) {
                usersMap.put(res.getData().get(i).getId().toString(), null);
            }
            Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(0).getId(), currentPage, 9999);
            requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                avi.hide();
                deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, resDeptUser.getData()));
                usersMap.put(departmentsResponses.get(0).getId().toString(), resDeptUser.getData());
            }, err -> {

            });
            adapter.notifyDataSetChanged();
            deptLv.setAdapter(adapter);
        }, err -> Toast.makeText(activity, "请求异常，请稍后重试", Toast.LENGTH_LONG).show());

        deptLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            if (usersMap.get(departmentsResponses.get(i).getId().toString()) != null) {
                deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, usersMap.get(departmentsResponses.get(i).getId().toString())));
            } else {
                Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(i).getId(), currentPage, 9999);
                avi.setVisibility(View.VISIBLE);
                deptUserLv.setVisibility(View.INVISIBLE);
                requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                    deptUserLv.setVisibility(View.VISIBLE);
                    avi.hide();
                    deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, resDeptUser.getData()));
                    usersMap.put(departmentsResponses.get(i).getId().toString(), resDeptUser.getData());
                }, err -> {

                });
            }
            if (selectIndex.get() != i) {
                departmentsResponses.get(i).setSelected(true);
                departmentsResponses.get(selectIndex.get()).setSelected(false);
                selectIndex.set(i);
            }
            adapter.notifyDataSetChanged();
        });

        deptUserLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            List<DepartmentsUserResponse> departmentsUserResponses = usersMap.get(departmentsResponses.get(selectIndex.get()).getId().toString());
            resDepartmentsUserResponse.setId(departmentsUserResponses.get(i).getId());
            resDepartmentsUserResponse.setRealname(departmentsUserResponses.get(i).getRealname());
            textView.setText(departmentsUserResponses.get(i).getRealname());
            textView.setVisibility(View.VISIBLE);
            if (Objects.nonNull(imageView)) {
                imageView.setVisibility(View.GONE);
            }
            dialog.dismiss();
        });
        dialog.show();
    }

    /**
     * 部门菜单
     *
     * @param activity
     * @param editText
     * @param resDepartmentsUserResponse
     */
    public static void getDepartmentsMenu(Activity activity, EditText editText, DepartmentsUserResponse resDepartmentsUserResponse) {
        int currentPage = 1;
        View dialogView = View.inflate(activity, R.layout.dialog_department_menu, null);
        Dialog dialog = new Dialog(activity, R.style.background_darkens_dialog_style);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(activity).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);

        ListView deptLv = dialogView.findViewById(R.id.area_list);
        ListView deptUserLv = dialogView.findViewById(R.id.staff_list);
        AVLoadingIndicatorView avi = dialogView.findViewById(R.id.avi);

        AtomicInteger selectIndex = new AtomicInteger();
        List<DepartmentsResponse> departmentsResponses = new ArrayList<>();
        Map<String, List<DepartmentsUserResponse>> usersMap = new HashMap<>();
        DepartmentMenuAdapter adapter = new DepartmentMenuAdapter(activity, R.layout.area_item_list, departmentsResponses);

        Retrofit mRetrofit = RetrofitClient.getInstance();
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> requestDept = new AsyncRequest<>();
        AsyncRequest<PageResponse<DepartmentsUserResponse>> requestDeptUser = new AsyncRequest<>();

        avi.setVisibility(View.VISIBLE);
        avi.show();
        requestDept.sendRequest(getDepartments, res -> {
            departmentsResponses.addAll(res.getData());
            departmentsResponses.get(0).setSelected(true);

            for (int i = 0; i < res.getData().size(); i++) {
                usersMap.put(res.getData().get(i).getId().toString(), null);
            }

            Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(0).getId(), currentPage, 9999);
            requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                avi.hide();
                deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, resDeptUser.getData()));
                usersMap.put(departmentsResponses.get(0).getId().toString(), resDeptUser.getData());
            }, err -> {

            });

            deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, departmentsResponses.get(0).getUsers()));
            adapter.notifyDataSetChanged();
            deptLv.setAdapter(adapter);
        }, err -> Toast.makeText(activity, "请求异常，请稍后重试", Toast.LENGTH_LONG).show());

        deptLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            if (usersMap.get(departmentsResponses.get(i).getId().toString()) != null) {
                deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, usersMap.get(departmentsResponses.get(i).getId().toString())));
            } else {
                Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(i).getId(), currentPage, 9999);
                avi.setVisibility(View.VISIBLE);
                deptUserLv.setVisibility(View.INVISIBLE);
                requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                    deptUserLv.setVisibility(View.VISIBLE);
                    avi.hide();
                    deptUserLv.setAdapter(new MySimpleAdapter(activity, R.layout.my_simple_item_list, resDeptUser.getData()));
                    usersMap.put(departmentsResponses.get(i).getId().toString(), resDeptUser.getData());
                }, err -> {

                });
            }
            if (selectIndex.get() != i) {
                departmentsResponses.get(i).setSelected(true);
                departmentsResponses.get(selectIndex.get()).setSelected(false);
                selectIndex.set(i);
            }
            adapter.notifyDataSetChanged();
        });

        deptUserLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            List<DepartmentsUserResponse> departmentsUserResponses = usersMap.get(departmentsResponses.get(selectIndex.get()).getId().toString());
            resDepartmentsUserResponse.setId(departmentsUserResponses.get(i).getId());
            resDepartmentsUserResponse.setRealname(departmentsUserResponses.get(i).getRealname());
            editText.setText(departmentsUserResponses.get(i).getRealname());
            dialog.dismiss();
        });
        dialog.show();
    }

    /**
     * 部门多选菜单
     *
     * @param activity
     * @param listView
     * @param helperList
     */
    public static void getDepartmentsMultipleChoiceMenu(Activity activity, ListView listView, List<DepartmentsUserResponse> helperList) {
        View dialogView = View.inflate(activity, R.layout.dialog_department_menu, null);
        Dialog dialog = new Dialog(activity, R.style.background_darkens_dialog_style);
        dialog.setContentView(dialogView);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (ScreenSizeUtils.getInstance(activity).getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);

        //获取ListView
        ListView deptLv = dialogView.findViewById(R.id.area_list);
        ListView deptUserLv = dialogView.findViewById(R.id.staff_list);
        AVLoadingIndicatorView avi = dialogView.findViewById(R.id.avi);

        //设置初始大区选项
        AtomicInteger selectIndex = new AtomicInteger();
        List<DepartmentsResponse> departmentsResponses = new ArrayList<>();
        List<DepartmentsUserResponse> departmentsUserResponses = new ArrayList<>();
        Map<String, List<DepartmentsUserResponse>> usersMap = new HashMap<>();
        DepartmentMenuAdapter adapter = new DepartmentMenuAdapter(activity, R.layout.area_item_list, departmentsResponses);
        DepartmentsCheckedAdapter checkedAdapter = new DepartmentsCheckedAdapter(activity, R.layout.checked_item_list, departmentsUserResponses);

        Retrofit mRetrofit = RetrofitClient.getInstance();
        DepartmentsApi departmentsApi = mRetrofit.create(DepartmentsApi.class);
        Call<PageResponse<DepartmentsResponse>> getDepartments = departmentsApi.getDepartments();
        AsyncRequest<PageResponse<DepartmentsResponse>> request = new AsyncRequest<>();
        AsyncRequest<PageResponse<DepartmentsUserResponse>> requestDeptUser = new AsyncRequest<>();

        avi.setVisibility(View.VISIBLE);
        avi.show();
        request.sendRequest(getDepartments, res -> {
            departmentsResponses.addAll(res.getData());
            departmentsResponses.get(0).setSelected(true);
            for (int i = 0; i < res.getData().size(); i++) {
                usersMap.put(res.getData().get(i).getId().toString(), null);
            }
            Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(0).getId(), 1, 9999);
            requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                avi.hide();
                usersMap.put(departmentsResponses.get(0).getId().toString(), resDeptUser.getData());
                departmentsUserResponses.addAll(usersMap.get(departmentsResponses.get(0).getId().toString()));
                checkedAdapter.notifyDataSetChanged();
                deptUserLv.setAdapter(checkedAdapter);
            }, err -> {

            });

            adapter.notifyDataSetChanged();
            deptLv.setAdapter(adapter);
        }, err -> {

        });

        //设置大区点击事件
        deptLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            if (selectIndex.get() != i) {
                departmentsResponses.get(i).setSelected(true);
                departmentsResponses.get(selectIndex.get()).setSelected(false);
                selectIndex.set(i);
            }
            if (usersMap.get(departmentsResponses.get(i).getId().toString()) != null) {
                departmentsUserResponses.clear();
                departmentsUserResponses.addAll(usersMap.get(departmentsResponses.get(i).getId().toString()));
                checkedAdapter.notifyDataSetChanged();
            } else {
                Call<PageResponse<DepartmentsUserResponse>> departmentUsers = departmentsApi.getDepartmentUsers(departmentsResponses.get(i).getId(), 1, 9999);
                avi.setVisibility(View.VISIBLE);
                deptUserLv.setVisibility(View.INVISIBLE);
                requestDeptUser.sendRequest(departmentUsers, resDeptUser -> {
                    deptUserLv.setVisibility(View.VISIBLE);
                    avi.hide();
                    usersMap.put(departmentsResponses.get(i).getId().toString(), resDeptUser.getData());
                    departmentsUserResponses.clear();
                    departmentsUserResponses.addAll(usersMap.get(departmentsResponses.get(i).getId().toString()));
                    checkedAdapter.notifyDataSetChanged();
                }, err -> {

                });
            }
            adapter.notifyDataSetChanged();

        });

        //设置员工点击事件
        deptUserLv.setOnItemClickListener((adapterView1, view1, i, l) -> {
            //设置员工选中状态
            usersMap.get(departmentsResponses.get(selectIndex.get()).getId().toString()).get(i).setItemChecked(!usersMap.get(departmentsResponses.get(selectIndex.get()).getId().toString()).get(i).getItemChecked());
            checkedAdapter.notifyDataSetChanged();
        });

        dialog.setOnDismissListener(v -> {
            //获取选中的员工
            for (Map.Entry<String, List<DepartmentsUserResponse>> entry : usersMap.entrySet()) {
                if (entry.getValue() != null) {
                    for (DepartmentsUserResponse checkedInfo : entry.getValue()) {
                        if (checkedInfo.getItemChecked()) {
                            helperList.add(checkedInfo);
                        }
                    }
                }
            }
            ViewUtils.setListViewHeightBasedOnChildren(listView);
            listView.setVisibility(View.VISIBLE);
        });
        dialog.show();
    }

    /**
     * 选择今天以后的时间
     *
     * @param activity
     * @param timeText
     */
    public static void selectLaterTimeDialog(Activity activity, TextView timeText) {
        //获取Calendar对象，用于获取当前时间
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //实例化DatePickerDialog对象
        DatePickerDialog datePickerDialog = new DatePickerDialog(activity, (view, selectedYear, monthOfYear, dayOfMonth) -> {
            if (selectedYear < year) {
                Toast.makeText(activity, "不能选择过去的时间", Toast.LENGTH_SHORT).show();
                return;
            } else {
                if ((monthOfYear) < month) {
                    Toast.makeText(activity, "不能选择过去的时间", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (dayOfMonth < day) {
                        Toast.makeText(activity, "不能选择过去的时间", Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        //因为monthOfYear会比实际月份少一月所以这边要加1
                        String selectDate = selectedYear + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                        timeText.setText(selectDate);
                        timeText.setTextColor(Color.parseColor("#101010"));
                    }
                }
            }
        }, year, month, day);
        //弹出选择日期对话框
        datePickerDialog.show();
    }

    /**
     * 选择时间
     *
     * @param activity
     * @param timeText
     */
    public static void selectTime(Activity activity, EditText timeText) {
        //获取Calendar对象，用于获取当前时间
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        //实例化DatePickerDialog对象
        DatePickerDialog datePickerDialog = new DatePickerDialog(activity, (view, selectedYear, monthOfYear, dayOfMonth) -> {
            //因为monthOfYear会比实际月份少一月所以这边要加1
            String selectDate = selectedYear + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
            timeText.setText(selectDate);
        }, year, month, day);
        //弹出选择日期对话框
        datePickerDialog.show();
    }

    /**
     * 选择产品维保时间
     *
     * @param activity
     * @param startTimeText
     * @param endTimeText
     * @param sum
     * @param flag
     */
    public static void selectProductMaintenanceTime(Activity activity, EditText startTimeText, EditText endTimeText, int sum, Boolean flag) {
        //获取Calendar对象，用于获取当前时间
        LocalDate nowDate = LocalDate.now();
        //实例化DatePickerDialog对象
        DatePickerDialog datePickerDialog = new DatePickerDialog(activity, (view, selectedYear, monthOfYear, dayOfMonth) -> {
            monthOfYear = monthOfYear + 1;
            LocalDate selectedDate = LocalDate.of(selectedYear, monthOfYear, dayOfMonth);
            if (flag) {
                String dateStr = selectedDate.getYear() + "-" + (selectedDate.getMonthValue()) + "-" + selectedDate.getDayOfMonth();
                startTimeText.setText(dateStr);
                selectedDate = selectedDate.plusMonths(sum).minusDays(1);
                dateStr = selectedDate.getYear() + "-" + (selectedDate.getMonthValue()) + "-" + selectedDate.getDayOfMonth();
                endTimeText.setText(dateStr);
            } else {
                String dateStr = selectedDate.getYear() + "-" + (selectedDate.getMonthValue()) + "-" + selectedDate.getDayOfMonth();
                endTimeText.setText(dateStr);
                selectedDate = selectedDate.minusMonths(sum).plusDays(1);
                dateStr = selectedDate.getYear() + "-" + (selectedDate.getMonthValue()) + "-" + selectedDate.getDayOfMonth();
                startTimeText.setText(dateStr);
            }
        }, nowDate.getYear(), nowDate.getMonthValue(), nowDate.getDayOfMonth());
        //弹出选择日期对话框
        datePickerDialog.show();
    }

    /**
     * 设置Spinner
     *
     * @param context
     * @param spinner
     * @param array
     * @param index
     */
    public static void setSpinnerAdapter(Context context, Spinner spinner, String[] array, int index) {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(context,  R.layout.spinner_simple_item , array);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(index);
    }

    /**
     * 设置EditText的监听
     *
     * @param editText
     */
    public static void setEditTextListener(EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e(TAG, "beforeTextChanged: " + "输入后" + s.toString());
            }

        });
    }
}